package kr.hkit.androidcomplete03.ch26;

import kr.hkit.androidcomplete03.R;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class SQLiteTest extends Activity {
	WordDBHelper mHelper;
	ListView list;
	WordDAO dao;
	SimpleCursorAdapter cAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sqlitetest);

		mHelper = new WordDBHelper(this);
		list = (ListView) findViewById(R.id.list);
		dao = WordDAO.open(this);
	}

	public void mOnClick(View v) {
		boolean result;
		String str = null;

		switch (v.getId()) {
		case R.id.insertBtn:
			EditText eng = (EditText) findViewById(R.id.engEdit);
			EditText han = (EditText) findViewById(R.id.hanEdit);
			result = dao.insert(eng.getText().toString(), han.getText().toString());
			str = result ? "Insert Success" : "Insert Fail";
			eng.setText("");
			han.setText("");
			break;
		case R.id.deleteAllBtn:
			result = dao.deleteAll();
			str = result ? "DeleteAll Success" : "DeleteAll Fail";
			break;
		case R.id.deleteBtn:
			EditText num = (EditText) findViewById(R.id.deleteBtn);
			result = dao.delete(Integer.parseInt(num.getText().toString()));
			str = result? "Delete Success":"Delete Fail";
			num.setText("");
			break;
		case R.id.updateBtn:
			EditText updateNum = (EditText) findViewById(R.id.updateNum);
			EditText updateEng = (EditText) findViewById(R.id.updateEng);
			EditText updateHan = (EditText) findViewById(R.id.updateHan);
			int id = Integer.parseInt(updateNum.getText().toString());
			
			result = dao.update(id, updateEng.getText().toString(), updateHan.getText().toString());
			str = result? "Update Success":"Update Fail";
			updateNum.setText("");
			updateEng.setText("");
			updateHan.setText("");
			break;
		case R.id.selectBtn:
			Cursor cursor = dao.selectAll();
			/*startManagingCursor(cursor);
			SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
					R.layout.listrow, 
					cursor, 
					new String[] { "_id", "eng", "han" }, 
					new int[] { R.id.listnum, R.id.listeng, R.id.listhan });*/
			
			SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
					R.layout.listrow, 
					cursor, 
					new String[] { "_id", "eng", "han" }, 
					new int[] { R.id.listnum, R.id.listeng, R.id.listhan }
					, SimpleCursorAdapter.NO_SELECTION);
			list.setAdapter(adapter);
			str = "Select Success";
			break;

		}

		Toast.makeText(this, str, Toast.LENGTH_LONG).show();

	}

	@Override
	protected void onPause() {
		super.onPause();
		dao.close();
	}
}
